package com.open.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.open.annotation.Limit;
import com.open.bean.DrawImg;
import com.open.bean.IpWhite;
import com.open.component.JwtComponent;
import com.open.result.OpenResult;
import com.open.server.TextTranslateServer;
import com.open.service.DrawImgService;
import com.open.service.IpWhiteService;
import com.open.util.GenerateAppKeyUtil;
import com.open.util.Md5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author tanyongpeng
 * <p>des</p>
 **/
@RestController
@RequestMapping("/request/open")
@Slf4j
public class OpenAIImgController {

    @Autowired
    IpWhiteService ipWhiteService;

    @Autowired
    DrawImgService drawImgService;

    @Autowired
    JwtComponent jwtComponent;

    @Autowired
    TextTranslateServer textTranslateServer;

    @PostMapping("/ai/draw/img")
    @Limit
    public String aiDraw(@RequestBody JSONObject jsonObject){
        log.info("绘画入参==========={}",jsonObject.toString());
        DrawImg drawImg = null;
        try {
            if (jsonObject.toString().contains("\\n")){
                String param = jsonObject.toString().replaceAll("\\\\n", "");
                jsonObject = JSONUtil.parseObj(param);
            }
            if (StrUtil.isBlank(jsonObject.getStr("app_key"))){
                return returnResult(-5,"","缺少”app_key“参数",0L,null);
            }
            drawImg = new DrawImg();
            IpWhite ipWhite = ipWhiteService.lambdaQuery().eq(IpWhite::getAppKey,jsonObject.getStr("app_key")).one();
            if (ipWhite == null) {
                return returnResult(-7,"","app_key校验错误",0L,null);
            }
            drawImg.setEmail(ipWhite.getEmail());
            drawImg.setWid(ipWhite.getWid());
            drawImg.setCreateTime(new Date());
            if (StrUtil.isBlank(jsonObject.getStr("prompt"))){
                return returnResult(-2,"","缺少”prompt“参数",0L,drawImg);
            }
            if (jsonObject.getStr("prompt").length() >= 1500){
                return returnResult(-3,"","prompt参数值过长",0L,drawImg);
            }
            drawImg.setDrawPrompt(jsonObject.getStr("prompt"));
            String prompt = textTranslateServer.textTranslate(jsonObject.getStr("prompt"));
            log.info("翻译后的文本：{}",prompt);
            if (StrUtil.isBlank(prompt)){
                return returnResult(-6,"","翻译失败，请联系作者",0L,drawImg);
            }
            log.info("开始绘画=================");
            String body = HttpRequest.post("https://app.baseten.co/applications/VBlnMVP/production/worklets/v0V6yV0/invoke")
                    .header("content-type", "application/json")
                    .header("cookie", "_ga=GA1.1.1258043229.1684200812; csrftoken=xrEKWIEt6Lblmtput9y5Jn5HzNhRNIcdGfM3MQQjB2EJPifP2RkBK4XZWTS3UXYn; __hstc=148795176.2ab910af85cc93bf6d4cb34ed667103a.1684200815883.1684200815883.1684200815883.1; hubspotutk=2ab910af85cc93bf6d4cb34ed667103a; __hssrc=1; intercom-id-kol4lyw4=7dd57e8d-f2a8-4fc2-ab82-214e3b23f14c; intercom-session-kol4lyw4=; intercom-device-id-kol4lyw4=46a84014-c01b-437f-abd3-d7532291f26f; mp_ee10470651a1b51008f32cde33152c0b_mixpanel=%7B%22distinct_id%22%3A%20%221882230ef0b17-0ee2f935208aaf-26021151-13c680-1882230ef0c1658%22%2C%22%24device_id%22%3A%20%221882230ef0b17-0ee2f935208aaf-26021151-13c680-1882230ef0c1658%22%2C%22%24initial_referrer%22%3A%20%22%24direct%22%2C%22%24initial_referring_domain%22%3A%20%22%24direct%22%7D; __hssc=148795176.5.1684200815883; _ga_NYTBYY5CMZ=GS1.1.1684200812.1.1.1684200863.0.0.0")
                    .header("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36")
                    .header("x-csrftoken", "xrEKWIEt6Lblmtput9y5Jn5HzNhRNIcdGfM3MQQjB2EJPifP2RkBK4XZWTS3UXYn")
                    .header("x-operating-workflow-id", "VBlnMVP")
                    .charset("utf-8").timeout(1000 * (60 * 5))
                    .body("{\"worklet_input\":{\"prompt\":\"" + prompt + "\"}}")
                    .execute().body();
            log.info("请求的结果：{}",body);
            JSONObject resultJson = JSONUtil.parseObj(body);
            if (resultJson.getBool("success")) {
                return returnResult(200,resultJson.getStr("worklet_output"),"成功",resultJson.getLong("latency_ms"),drawImg);
            }else {
                return returnResult(-4,"","画图失败，请稍后再试",0L,drawImg);
            }
        }catch (Exception e){
            e.printStackTrace();
            return returnResult(-1,"","内部程序错误",0L,drawImg);
        }
    }

    @PostMapping("/update/app/key")
    public OpenResult updateAppKey(HttpServletRequest request){
        String wId = jwtComponent.getUserWId(request);
        IpWhite ipWhite = ipWhiteService.getById(wId);
        String appKey = GenerateAppKeyUtil.getAppKey(String.valueOf(ipWhite.getWid()),ipWhite.getNikeName());
        ipWhiteService.lambdaUpdate()
                .set(IpWhite::getAppKey,appKey)
                .eq(IpWhite::getWid,wId).update();
        return OpenResult.success(appKey);
    }

    public String returnResult(Integer code,String base64,String msg,Long ms,DrawImg drawImg){
        JSONObject res = new JSONObject();
        res.set("code",code);
        res.set("img_base64",base64);
        res.set("message",msg);
        res.set("ms",ms);
        if (drawImg != null){
            drawImg.setRequestStatus(code);
            drawImg.setImgBase(base64);
            drawImg.setDrawTime(ms.intValue());
            drawImgService.save(drawImg);
        }
        return res.toString();
    }
}
